//
//  ZLNetWorkManager-Extension.swift
//  ZLWeibo
//
//  Created by zhanglongtao on 16/12/20.
//  Copyright © 2016年 hanju001. All rights reserved.
//

import Foundation

//MARK --封装新浪微博的网络请求
extension ZLNetWorkManager{
    
    //返回未读数据
    func unReadCount(completion: @escaping (_ count: Int) -> ()) {
        
        guard let uid = userAcount.uid else{
            
            return
        }
        let urlString = "https://rm.api.weibo.com/2/remind/unread_count.json"
        let params = ["uid": uid]
        tokenRequest(URLString: urlString, parameters: params as [String : AnyObject]?) { (json, isSuccess) in
            
            let dic = json as? [String: AnyObject]
            
            let count = dic?["status"] as? Int
            completion(count ?? 0)
            print(json ?? "")
        }
        
    }
    func statusList(since_id: Int64,max_id: Int64, completion: @escaping (_ list: [[String: AnyObject]], _ isSuccess: Bool)->()) {
        
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
       
        let params = ["since_id": "\(since_id)","max_id": "\(max_id > 0 ? max_id - 1 : 0)"]
        tokenRequest(method: .GET, URLString: urlString, parameters: params as [String : AnyObject]?) { (json, isSuccesss) in
            
            if isSuccesss{
                
                // 从 json 中获取 statuses 字典数组
                // 如果 as? 失败，result = nil
                // 提示：服务器返回的字典数组，就是按照时间的倒序排序的
                guard let result = json?["statuses"] as? [[String: AnyObject]] else
                {
                    completion([[:]], false)
                    return
                }
                
                completion(result, isSuccesss)
                
                
            }
        }
        
    }
}
/// 发布微博
extension ZLNetWorkManager {
    //发布微博
    func postStatus(status: String,iamge: UIImage? = nil, completion: @escaping (_ result: AnyObject?, _ isSuccess: Bool)->()) -> () {
        
        
        var url = "https://api.weibo.com/2/statuses/update.json"
        
        if iamge != nil{
            url = "https://upload.api.weibo.com/2/statuses/upload.json"
        }
        
        let params = ["status": status]
        var name: String?
        var data: Data?
        
        if iamge != nil {
            
            name = "pic"
            data = UIImagePNGRepresentation(iamge!)
        }
        tokenRequest(method: .POST, URLString: url, parameters: params as [String : AnyObject]?, name: name, data: data) { (json, isSuccess) in
            completion(json, isSuccess)
        }

    }
}
// MARK -- 用户信息
extension ZLNetWorkManager{
    
    //加载当前用户信息
    func loadUserInfo(completion: @escaping (_ dict: [String: AnyObject])->()) {
        
        guard let uid = userAcount.uid else {
            
            return
        }
        let url = "https://api.weibo.com/2/users/show.json"
        
        let params = ["uid": uid]
        
        tokenRequest(method: .GET, URLString: url, parameters: params as [String : AnyObject]?) { (json, isSuccess) in
            
            print("\(json)")
            //完成回调
            completion((json as? [String: AnyObject]) ?? [:])
        }
        
    }
}
//MARK -- OAuth相关的方法
extension ZLNetWorkManager{
    
    func loadAccessToken(code: String, completion: @escaping (_ isSuccess: Bool)->()) {
        
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let paramsters = ["client_id": "\(ZLAPPKEY)","client_secret": "\(ZLAppSecret)","grant_type": "authorization_code","code": code,"redirect_uri": "\(ZLRedirectUrl)"]
        //发起网络请求
        request(method: .POST, URLString: urlString, parameters: paramsters as [String : AnyObject]?) { (json, isSsucess) in
            
            //直接字典设置 userAcount的属性
            self.userAcount.yy_modelSet(withJSON: (json as? [String: AnyObject]) ?? [:])
            //uid  5890823822
            //print("json:\(json)")
            
           
            //加载当前用户信息
            self.loadUserInfo(completion: { (dict) in
                
                print(dict)
                self.userAcount.screen_name = dict["screen_name"] as! String?
                self.userAcount.avatar_large = dict["avatar_large"] as! String?
                
                 self.userAcount.savaAccount()
                print(self.userAcount)
                //用户信息加载完成在回调
                completion(isSsucess)
            })
            
            
        }
    }
}
